<?php
class UsersController extends AppController {

	public $name 		= 'Users';
	public $components 	= array('Mailer');
	public $uses 		= array('User', 'TmpEmail', 'Timezone');
	/**
	 * @var User
	 */
	public $User;
	/**
	 * @var AuthComponent
	 */
	public $Auth;
	/**
	 * @var MailerComponent
	 */
	public $Mailer;
	/**
	 * @var TmpEmail
	 */
	public $TmpEmail;
	/**
	 * @var Timezone
	 */
	public $Timezone;
	
	
	public function beforeFilter() {
		parent::beforeFilter();
		$this->Auth->allow('register', 'confirm', 'recover');
		if ($this->action == 'register' OR $this->action == 'account') {
			$this->Auth->authenticate = $this->User;
		}
	}
	
	public function afterFilter() {
		if ($this->Auth->isAuthorized()) {
			if ($this->action == 'register' OR $this->action == 'login' OR $this->action == 'recover') {
				$this->Session->setFlash(__('Already logged in.', true));
				$this->redirect('/');
			}
		}
	}
	
	public function login() {
	}
	
	public function logout($message=''){
		if ($message == '') {
			$message = __('Logout', true);
		}
		$this->Session->setFlash($message);
	    $this->redirect($this->Auth->logout());
	}
	
	function index() {
		$this->redirect(array('action'=>'account'));
	}

	function register() {
		if (!Configure::read('User.useRegister')) {
			$this->Session->setFlash(__('Registration is not available at this moment.', true));
			$this->redirect('/');
			return $this->respondFailed(1);
		} else {
			if (Configure::read('System.useTimezone')) {
				$this->set('timezones', $this->Timezone->toOptions($this->Timezone->find('all')));
			}
			if (!empty($this->data)) {
				if (!Configure::read('User.useUsername')) {
					unset($this->User->validate['username']);
					if (isset($this->data['User']['username'])) {
						unset($this->data['User']['username']);
					}
				}
				$this->User->create();
				if ($this->User->save($this->data)) {
					$this->Session->setFlash(__('The user has been saved. Please confirm your email address.', true));
					if (Configure::read('User.useUsername')) {
						$this->set('confirmUrl', Configure::read('System.appAddress').'/confirm/'.md5($this->User->id.'-'.$this->data['User']['username'].'-'.$this->data['User']['email']));
					} else {
						$this->set('confirmUrl', Configure::read('System.appAddress').'/confirm/'.md5($this->User->id.'-'.$this->data['User']['email']));
					}
					$this->Mailer->sendRegistrationEmail($this->data['User']['email']);
					$this->render('register_success');
					return $this->respondOk(3);
				} else {
					$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
					return $this->respondFailed(4, $this->User->validationErrors);
				}
			}
			return $this->respondOk(2);
		}
	}
	
	function confirm($code='', $emailChange='') {
		if ($code != '' AND $emailChange != '') {
			$conditions = array(
				"MD5(CONCAT(user_id, '-', new_email, '-', old_email))"=>$code, 
				"UNIX_TIMESTAMP(created)+".Configure::read('System.confirmExpire')." > " => time()
				);
			$email = $this->TmpEmail->find($conditions, null, array('created DESC'));
			$user = $this->User->find(array($this->User->name.'.id'=>$email['TmpEmail']['user_id']));
			if ($user) {
				$this->data['User']['email'] = $email['TmpEmail']['new_email'];
				$this->User->id = $user['User']['id'];
				if ($this->User->save($this->data)) {
					$this->Session->setFlash(__('Email has been confirmed.', true));
					if ($this->Auth->isAuthorized()) {
						$user 	= $this->Auth->user();
						if ($user['User']['id'] == $email['TmpEmail']['user_id']) {
							$this->updateUserSession($email['TmpEmail']['user_id']);
						}
					}
				} else {
					$this->Session->setFlash(__('Email could not be confirmed.', true));
				}
				return;
			}
		} else if ($code != '') {
			if (Configure::read('User.useUsername')) {
				$conditions = array("MD5(CONCAT(`User`.`id`, '-', username, '-', email))"=>$code);
			} else {
				$conditions = array("MD5(CONCAT(`User`.`id`, '-', email))"=>$code);
			}
			$conditions['active'] = 0;
			$conditions["UNIX_TIMESTAMP(created)+".Configure::read('System.confirmExpire')." > "] = time();
			$user = $this->User->find($conditions);
			if ($user) {
				$this->data['User']['active'] = '1';
				$this->User->id = $user['User']['id'];
				if ($this->User->save($this->data)) {
					$this->Session->setFlash(__('Account has been confirmed.', true));
				} else {
					$this->Session->setFlash(__('Account could not be confirmed.', true));
				}
				return;
			}
		}
		$this->Session->setFlash(__('Invalid confirmation code.', true));
	}
	
	function recover() {
		if (!empty($this->data)) {
			$Validation =& Validation::getInstance();
			if ($Validation->email($this->data['User']['email'])) {
				$user = $this->User->find(array('email'=>$this->data['User']['email'], 'active'=>'1'));
				if ($user) {
					$password = $this->User->generatePassword();
					$this->data['User']['password'] = $password;
					unset($this->User->validate['password']['checkOldUp']);
					unset($this->User->validate['password']['matchUp']);
					$this->User->id = $user['User']['id'];
					if ($this->User->save($this->data)) {
						$this->Session->setFlash(__('Password was resetted. Please check your email address.', true));
						$this->set('password', $password);
						$this->Mailer->sendRecoveryEmail($this->data['User']['email']);
						$this->render('recover_success');
						return;
					}
				}
			}
			$this->Session->setFlash(__('Password recovery failed.', true));
		}
	}

	function account() {
		$user 			= $this->Auth->user();
		$id 			= $user['User']['id'];
		$emailUpdate 	= '';
		if (Configure::read('System.useTimezone')) {
			$this->set('timezones', $this->Timezone->toOptions($this->Timezone->find('all')));
		}
		if (!empty($this->data)) {
			if (Configure::read('User.useDisableAccount') AND isset($this->data['User']['disable']) AND $this->data['User']['disable'] == 1) {
				$this->User->delete($id);
				return $this->logout(__('Your account has been deleted.', true));
			}
			$this->data['User']['id'] = $id;
			if ($this->data['User']['password'] == '') {
				unset($this->data['User']['password']);
				unset($this->data['User']['password_confirm']);
				unset($this->data['User']['old_password']);
			}
			if (isset($this->data['User']['username'])) {
				unset($this->data['User']['username']);
			}
			if ($this->data['User']['email'] != $user['User']['email']) {
				$Validation =& Validation::getInstance();
				if ($Validation->email($this->data['User']['email']) AND $this->User->isUnique(array('email'=>$this->data['User']['email']))) {
					$this->TmpEmail->create();
					if ($this->TmpEmail->save(array('user_id'=>$id, 'old_email'=>$user['User']['email'], 'new_email'=>$this->data['User']['email']))) {
						$emailUpdate = __('Please confirm your new email.', true);
						$this->set('confirmUrl', Configure::read('System.appAddress') .'/confirm/'.md5($id.'-'.$this->data['User']['email'].'-'.$user['User']['email']).'/'.md5($this->User->generatePassword(8)));
						$this->Mailer->sendChangeEmail($this->data['User']['email']);
					} else {
						$this->Session->setFlash(__('Email address could not be saved.', true));
						return;
					}
					$this->data['User']['email'] = $user['User']['email'];
				}
			}
			if ($this->User->save($this->data)) {
				$this->updateUserSession($id);
				$this->Session->setFlash(__('The user has been saved. ', true).$emailUpdate);
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
			}
		} else {
			$this->data = $this->User->read(null, $id);
			$this->data['User']['password'] = '';
		}
	}
}